package com.maotai.llzhou.servlet;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rk.RuoKuai;

import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.HuaRunInfo;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.HuaRunHttpClientUtil;


@Controller 
public class MaotaiController {
//	private final Log log = LogFactory.getLog(MaotaiController.class);
    
    @Resource
	private MaotaiService maotaiService;
    @ResponseBody
   	@RequestMapping(value="/initDevice",produces = {"application/json;charset=UTF-8"}) 
   	public String initDevice(@RequestBody String param)
   	{
       	System.out.println(param);
       	String[] dates = param.split("&");
//    	String code = dates[0].split("=")[1];
//    	String code = dates[0].split("=")[1];
//    	String code = dates[0].split("=")[1];
//    	String code = dates[0].split("=")[1];
//       	String returtnstr = "{}";
//       	try {
//			int mtBizId = 0;
//			String auth = zhanghao.get("auth")+"";
//			String zimId = "";
//            String bizId = "";
//            String name = zhanghao.get("name")+"";
//            String certNumber = zhanghao.get("certNumber")+"";
//            if("".equals(auth)||"null".equals(auth)){
//            	shenfenMap.put("usestatus", "0");
//				maotaiService.updateShenFenStatus(shenfenMap);
//            	zhanghao.put("initstatus", "0");
//				maotaiService.updateZhanghaoInitStatus(zhanghao);
//	        	return;
//            }
//            
//			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
//			// 增加代理
//			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
//			
//			/**
//			 * 新增扫脸功能
//			 */
//			//访问预约页面
//			mwc = hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_BEGIN_URL, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
//	        //点击预约
//	        String signurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/switch?sign="+JSUtil.excuFunctionA("EMAOTAI_"+zhanghao.get("memberId"))+"&appCode=1&_t="+System.currentTimeMillis();
//	        mwc = hcu.sendHttpGetProxy(signurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
//	        //2018-09-08
//	        //信用体系
//	        String auditurl = "https://i.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get?appCode=1&_t="+System.currentTimeMillis();
//	        mwc = hcu.sendHttpGetProxy(auditurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
//	        
//	        //清楚下缓存
//	        //String clearurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId=2&appCode=1&_t="+System.currentTimeMillis();
//	        //mwc = hcu.sendHttpGetProxy(clearurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
//	        //TODO
//			//扫码接收预约
//	        //发起二维码扫描
//	        String compressurl1 = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/compress?mtBizId=2&faceverify=scan&auth="+auth+"&appCode=1&_t="+System.currentTimeMillis();
//	        String yuyuereferer1 = "https://www.emaotai.cn/smartsales-b2c-web-pc/sign/signUp?info="+auth;
//	        //接收二维码扫描
//	        mwc = hcu.sendHttpGetProxy(compressurl1, mwc, config, yuyuereferer1);
//	        System.out.println(zhanghao.get("code")+"----提示信用二维码页面-------"+mwc.getContent());
//	        //信用扫描二维码
//	        String auditUrl = "https://i.cmaotai.com/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get";
//	        mwc = hcu.sendHttpGetAppProxy(auditUrl, mwc, config, null);
//	        System.out.println(zhanghao.get("code")+"----获取实名结果----" + mwc.getContent());
//	        JSONObject resultCode = JSONObject.parseObject(mwc.getContent());
//	        
//	        if(resultCode.getIntValue("resultCode")==401){
//	        	zhanghao.put("loginstatus", "0");
//	        	maotaiService.updateZhanghaoLoginStatus(zhanghao);
//	        	zhanghao.put("initstatus", "0");
//				maotaiService.updateZhanghaoInitStatus(zhanghao);
//				shenfenMap.put("usestatus", "0");
//				maotaiService.updateShenFenStatus(shenfenMap);
//	        	return;
//	        }
//            if(resultCode.getIntValue("resultCode")==-1){
//            	shenfenMap.put("usestatus", "0");
//				maotaiService.updateShenFenStatus(shenfenMap);
//				zhanghao.put("initstatus", "x");
//				maotaiService.updateZhanghaoInitStatus(zhanghao);
//            	return;
//            }
//	        if(mwc.getContent().contains("docNo")){
//	        	JSONObject data = JSONObject.parseObject(mwc.getContent()).getJSONObject("data");
//	        	String docNo = data.getString("docNo");
//	        	String realName = data.getString("realName");
//	        	zhanghao.put("docNo", docNo);
//	        	zhanghao.put("realName", realName);
//	        	maotaiService.insertMaotaiAudit(zhanghao);
//	        	shenfenMap.put("usestatus", "0");
//				maotaiService.updateShenFenStatus(shenfenMap);
//	        	return;
//	        }
//	        Thread.sleep(5000);
//	        //Map<String, Object> tokenMap = maotaiService.getTokenRandom();
//	        shenfenMap = maotaiService.getShenFengRandom();
//	        String token = tokenMap.get("token")+"";
//	        //获得metainfo
//	        JSONObject uploadJ = new JSONObject();
//	        uploadJ.put("apdidToken","") ;
//	        uploadJ.put("appName","com.emaotai.ysapp") ;
//	        uploadJ.put("appVersion",ProductInfo.PRODUCT_VERSION) ;
//	        uploadJ.put("bioMetaInfo","3.3.0:98304,0") ;
//	        uploadJ.put("deviceModel","HTC Rezound"+""+System.currentTimeMillis()) ;
//	        uploadJ.put("deviceType","android") ;
//	        uploadJ.put("osVersion","6.0.1") ;
//	        uploadJ.put("zimVer","1.0.0") ;
//	        String realname = shenfenMap.get("name")+"";
//	        String shenfenzheng = shenfenMap.get("shenfenzheng")+"";
//	        String inturl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init";
//	        //System.out.println(certNumber+"----"+name);
//	        //String postData = "auditType=1&certNumber="+shenfenzheng+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(realname,"utf-8");
//	      String postData = "auditType=1&certNumber=320922198607240034&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName=%E5%91%A8%E4%BA%AE%E4%BA%AE";
//	        //String postData = "auditType=1&certNumber=341122198904270433&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode("王涛","utf-8");
//	        for(int i=0;i<10;i++) {
//	        	 mwc = hcu.sendHttpPostAppProxy(inturl, mwc, postData, config);
//	            // "bizId" : "EMAOTAI_20180814093735856536",
//	            System.out.println(zhanghao.get("code")+"----初始化信用摄像头----" + mwc.getContent());
//	            if(resultCode.getString("resultMsg").contains("失败")){
//		        	shenfenMap.put("usestatus", "0");
//					maotaiService.updateShenFenStatus(shenfenMap);
//					zhanghao.put("initstatus", "f");
//					maotaiService.updateZhanghaoInitStatus(zhanghao);
//					return;
//		        }
//	            if (mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
//	            	Thread.sleep(1000);
//	                continue;
//	            } else {
//	                break;
//	            }
//	            
//	        }
//	       
//	        //获取信用返回的data
//	        if(mwc!=null && mwc.getContent()!=null){
//	            JSONObject initJson = JSON.parseObject(mwc.getContent()).getJSONObject("data");
//	            zimId = initJson.getString("zimId");
//	            bizId = initJson.getString("bizId");
//	            
//	        }
       	return "";
   	}
	@ResponseBody
	@RequestMapping(value="/decodeImage",produces = {"application/text;charset=UTF-8"}) 
	public String decodeImage(@RequestBody String param)
	{
//		data:image/jpeg;base64, 
		param = param.replace("data:image/jpg;base64,", "");
//		String temp = ImageUtil.decodeImage(param);
		String temp =RuoKuai.createByBase64("vipwangtao888","WT985200","3040","95000","102790","3bbcf57ca4fb44f8b6134dd2c317de24",param);
		//{"Result":"fpxr","Id":"27a3809a-49e2-496e-bb1e-74489ad586bc"}
		JSONObject jObj = JSONObject.parseObject(temp);
		if(jObj!=null)
			return jObj.getString("Result");
		else return "";
	}
	@ResponseBody
	@RequestMapping(value="/queryMaotaiOrderItem",produces = {"application/json;charset=UTF-8"}) 
	public String queryMaotaiOrderItem(@RequestBody String param)
	{
    	String returtnstr = "{}";
    	String[] dates = param.split("&");
//    	JSONObject jj = JSONObject.fromObject(param);
//    	String startDate = jj.getString("startDate");
//    	String endDate = jj.getString("endDate");
    	String startDate = dates[0].split("=")[1];
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("startDate", startDate);
    	try {
			List<Map<String, Object>> list = maotaiService.queryMaotaiOrderItem(map);
			if(list!=null && list.size()>0){
				JSONArray jArr = JSONArray.fromObject(list);
				returtnstr = jArr.toString();
			}
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return returtnstr;
	}
	@ResponseBody
	@RequestMapping(value="/getMaotaiOrderItem",produces = {"application/json;charset=UTF-8"}) 
	public String getMaotaiOrderItem(@RequestBody String param)
	{
    	String returtnstr = "{}";
    	String[] dates = param.split("&");
    	String zfbcode = URLDecoder.decode(dates[0].split("=")[1]);
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("zfbcode", zfbcode);
    	try {
			List<Map<String, Object>> list = maotaiService.getMaotaiOrderItem(map);
			if(list!=null && list.size()>0){
				JSONArray jArr = JSONArray.fromObject(list);
				returtnstr = jArr.toString();
			}
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return returtnstr;
	}
	
	@ResponseBody
	@RequestMapping(value="/getMaotaiCodeItem",produces = {"application/json;charset=UTF-8"}) 
	public String getMaotaiCodeItem(@RequestBody String param)
	{
    	String returtnstr = "{}";
    	String[] dates = param.split("&");
//    	JSONObject jj = JSONObject.fromObject(param);
//    	String startDate = jj.getString("startDate");
//    	String endDate = jj.getString("endDate");
    	String zfbcode = URLDecoder.decode(dates[0].split("=")[1]);
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("zfbcode", zfbcode);
    	
    	try {
			List<Map<String, Object>> list = maotaiService.getMaotaiCodeItem(map);
			if(list!=null && list.size()>0){
				JSONArray jArr = JSONArray.fromObject(list);
				returtnstr = jArr.toString();
			}
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return returtnstr;
	}
	@ResponseBody
	@RequestMapping(value="/getNikeMobile",produces = {"application/text;charset=UTF-8"}) 
	public String getNikeMobile()
	{
    	String returtnstr = "{}";
    	
    	try {
			Map<String, Object> list = maotaiService.getNikeMobile();
			if(list!=null && list.size()>0){
				JSONArray jArr = JSONArray.fromObject(list);
				returtnstr = jArr.toString();
			}
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	System.out.println(returtnstr);
    	return returtnstr;
	}
	@ResponseBody
	@RequestMapping(value="/addcode",produces = {"application/json;charset=UTF-8"}) 
	public int addcode(@RequestBody String param)
	{
		int cou = 0;
    	String[] dates = param.split("&");
//    	JSONObject jj = JSONObject.fromObject(param);
//    	String startDate = jj.getString("startDate");
//    	String endDate = jj.getString("endDate");
    	String zfbcode = URLDecoder.decode(dates[0].split("=")[1]);
    	String code = dates[1].split("=")[1];
    	String pwd = dates[2].split("=")[1];
    	String tel = dates[3].split("=")[1];
    	String qq = dates[4].split("=")[1];
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("zfbcode", zfbcode);
    	map.put("code", code);
    	map.put("pwd", pwd);
    	map.put("tel", tel);
    	map.put("qq", qq);
    	try {
			cou = maotaiService.addMaotaiCode(map);
			
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return cou;
	}
	
	@ResponseBody
	@RequestMapping(value="/sendSMSVerifyCode",produces = {"application/json;charset=UTF-8"}) 
	public String sendSMSVerifyCode(@RequestBody String param) throws Exception
	{
		System.out.println(param);
		String telphone = param.split("=")[1];
		String telCodeUrl = "https://app.crv.com.cn/app_api/v1/dc-app-api/mobile/api/global/sendSMSVerifyCode";
		JSONObject jObj2 = new JSONObject();
		jObj2.put("phoneNumber", telphone);
		jObj2.put("type", 302);
		String data2 = "param="+URLEncoder.encode(jObj2.toJSONString());
		HuaRunHttpClientUtil huaRunHttp = HuaRunHttpClientUtil.getInstance();
		HuaRunInfo huaRunInfo = new HuaRunInfo();
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		String uniqueId = uuid.substring(0, 16);
		huaRunInfo.setUniqueId(uniqueId);
		huaRunInfo = huaRunHttp.sendHttpPostProxy(telCodeUrl, huaRunInfo,data2, null);
		System.out.println(uniqueId);
    	return uniqueId;
	}
	@ResponseBody
	@RequestMapping(value="/loginBySms",produces = {"application/json;charset=UTF-8"}) 
	public String loginBySms(@RequestBody String param) throws Exception
	{
		System.out.println(param);
		String[] dates = param.split("&");
    	String telphone = dates[0].split("=")[1];
    	String password = dates[1].split("=")[1];
    	String code = dates[2].split("=")[1];
    	String uniqueId = dates[3].split("=")[1];
    	String loginUrl = "https://app.crv.com.cn/app_api/v1/dc-app-api/mobile/api/user/loginBySms";
    	HuaRunHttpClientUtil huaRunHttp = HuaRunHttpClientUtil.getInstance();
		HuaRunInfo huaRunInfo = new HuaRunInfo();
		huaRunInfo.setUniqueId(uniqueId);
		//{"phone":"13372007847","code":"967251"}
		//param=%7B%22phone%22%3A%2213372007847%22%2C%22code%22%3A%22967251%22%7D
		JSONObject jObj = new JSONObject();
		jObj.put("phone", telphone);
		jObj.put("code", code);
		String data = "param="+URLEncoder.encode(jObj.toJSONString());
		huaRunInfo = huaRunHttp.sendHttpPostProxy(loginUrl, huaRunInfo, data, null);
		//{"data":{"inquire":1,"id":1103960,"loginTime":"2019-09-02 18:51:28","userSession":"3B5FC34325790EF8371C4E0117D2EEA7","loginName":"13372007847"},"stateCode":0}
		JSONObject content = JSONObject.parseObject(huaRunInfo.getContent());
		JSONObject jdata = content.getJSONObject("data");
		String userId = jdata.getString("id");
		String userSession = jdata.getString("userSession");
		huaRunInfo.setUserId(userId);
		huaRunInfo.setUserSession(userSession);
		String userInfoUrl = "https://app.crv.com.cn/app_api/v1/dc-app-api/mobile/api/user/info";
		huaRunInfo = huaRunHttp.sendHttpGetProxy(userInfoUrl, huaRunInfo, null);
		//{"data":{"inquire":0,"collectCount":0,"clerkCode":"","accountBalance":0,"nickname":"15895887847","uname":"周亮亮","unReceiveOrderCount":0,"unSendOrderCount":0,"unreadMessageCount":0,"id":1107261,"cardNo":"86400153877708","shopId":"A00C","unPayOrderCount":0,"mobile":"15895887847","loginName":"15895887847","ncmsMemberId":"7826514809038415953"},"stateCode":0}
		JSONObject userInfoData = JSONObject.parseObject(huaRunInfo.getContent()).getJSONObject("data");
		String ncmsMemberId = userInfoData.getString("ncmsMemberId");
		String shopId = userInfoData.getString("shopId");
		
		//执行登录操作
		Map<String, Object> mapList = new HashMap<String, Object>();
		mapList.put("telphone", telphone);
		mapList.put("password", password);
		mapList.put("userId", userId);
		mapList.put("uniqueId", uniqueId);
		mapList.put("userSession", userSession);
		mapList.put("ncmsMemberId", ncmsMemberId);
		mapList.put("shopId", shopId);
		mapList.put("jsessionId", huaRunInfo.getJsessionId());
		
		maotaiService.addHuaRunZhanghao(mapList);
    	return "登录成功";
	}
}
